package com.lwl.mini.mapping;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.lwl.mini.binding.BindingException;
import com.lwl.mini.util.ObjectUtils;
import lombok.Data;
import lombok.ToString;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author lwl
 * @create 2022/4/10 13:28
 */
public class Environment {

    private String url;
    private String username;
    private String driver;
    private String password;

    private volatile DataSource dataSource;

    public void addAttributes(Properties prop, String str){
        if(str.contains("url")){
            setUrl(prop.getProperty(str));
        }
        if(str.contains("username")){
            setUsername(prop.getProperty(str));
        }
        if(str.contains("driver")){
            setDriver(prop.getProperty(str));
        }
        if(str.contains("password")){
            setPassword(prop.getProperty(str));
        }
    }

    /**
     * 当前版本不支持指定数据源，默认数据源为Druid
     * 获取数据源
     * @return
     */
    public DataSource getDataSource() throws Exception {
        if(dataSource == null){
            synchronized (this){
                if(dataSource == null){
                    if(ObjectUtils.StringIsEmpty(url) || ObjectUtils.StringIsEmpty(username) || ObjectUtils.StringIsEmpty(password) || ObjectUtils.StringIsEmpty(driver)){
                        throw new BindingException("配置不完整,请检查连接数据库配置参数是否完整");
                    }
                    Properties properties = new Properties();
                    properties.put("url",url);
                    properties.put("username",username);
                    properties.put("password",password);
                    properties.put("driverClassName",driver);
                    this.dataSource = DruidDataSourceFactory.createDataSource(properties);
                }
            }
        }
        return dataSource;
    }

    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,username,password);
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
}
